package com.cskaoyan.controller.zyl_wxlogin;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.marketBean.LoginUserData;
import com.cskaoyan.bean.marketBean.MarketUser;
import com.cskaoyan.bean.marketBean.MarketUserExample;
import com.cskaoyan.controller.AuthController;
import com.cskaoyan.controller.wx.WxAuthController;
import com.cskaoyan.service.Zyl_Shopping_cart_Service.MarketCartService_zyl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.cskaoyan.controller.zyl_wxlogin.WechatUtil2.decryptData;


//shiro整合之后，在做具体的开发
//响应结果都是JSON，Controller组件上我们都用@RestController注解


@RestController
@RequestMapping("wx/auth")
public class AuthController_zyl_wx {


    @Autowired
    MarketCartService_zyl marketCartService_zyl;


/**
 * Shiro安全框架 → 视频课程 4个课时 → 认证（登录）
 * 如果参数比较少，类型比较简单的话，使用map来接收也可以
 */

/*
    @PostMapping("login_by_weixin")
    public void login_by_weixin(@RequestBody login_weixin map) {

        System.out.println("map = " + map);
    }*/


    /**
     * 解密用户敏感数据
     *
     * @param //iv 加密算法的初始向量
     * @return
     * @param// encryptedData 明文,加密数据
     * @param// code          用户允许登录后，回调内容会带上 code（有效期五分钟），开发者需要将 code 发送到开发者服务器后台，使用code 换取 session_key api，将 code 换成 openid 和 session_key
     */
    //login_by_weixin_getcode
  /*  @PostMapping("login_by_weixin")
    public Map login_by_weixin_getcode(@RequestBody login_weixin code, HttpServletRequest request) {


        *//*ServletContext servletContext = request.getServletContext();
        servletContext.setAttribute("code", code.getCode());*//*

        decodeUserInfo(code.getCode(), WX_zyl jm_date) ;

        return null;
    }*/
    @PostMapping("login_by_weixin")
    public BaseRespVo<LoginUserData> jm_date(@RequestBody WX_zyl wX_zyl) {

       /* ServletContext servletContext = request.getServletContext();
        String code = (String) servletContext.getAttribute("code");
*/
        String openid = decodeUserInfo(wX_zyl.getCode());

        HashMap<Object, Object> loginmap = new HashMap<>();


        loginmap.put("username", wX_zyl.getUserInfo().getNickName());
        loginmap.put("password", openid);

        MarketUserExample marketUserExample = new MarketUserExample();
        marketUserExample.createCriteria().andWeixinOpenidEqualTo(openid);
        marketUserExample.createCriteria().andNicknameEqualTo(wX_zyl.getUserInfo().getNickName());

        int size = marketCartService_zyl.selectByExample(marketUserExample).size();
        if (size == 0) {
            register_wx(wX_zyl, openid);
        }

        WxAuthController wxAuthController = new WxAuthController();

        BaseRespVo<LoginUserData> login1 = wxAuthController.login(loginmap);

        //  BaseRespVo<LoginUserData> login = authController.login(loginmap);

        return login1;
    }


    public String decodeUserInfo(String code) {

       /* String encryptedData = jm_date.getRes().getEncryptedData();
        String iv = jm_date.getRes().getIv();
        System.out.println("iv = " + iv);*/

        Map map = new HashMap();
        //登录凭证不能为空
        if (code == null || code.length() == 0) {
            map.put("status", 0);
            map.put("msg", "code 不能为空");
            return null;
        }
        //小程序唯一标识   (在微信小程序管理后台获取)
        String wxspAppid = "wx4bc41ebe4ceda388";
        //小程序的 app secret (在微信小程序管理后台获取)
        String wxspSecret = "59ad579999c20d80903ec67aed8f0b1a";
        //授权（必填）
        String grant_type = "authorization_code";

        // 1、向微信服务器 使用登录凭证 code 获取 session_key 和 openid
        //请求参数
        String params = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        //发送请求
        String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", params);
        System.out.println("sr = " + sr);
        //解析相应内容（转换成json对象）
        JSONObject json = JSONUtil.parseObj(sr);
        //获取会话密钥（session_key）
        String session_key = json.get("session_key").toString();
        //用户的唯一标识（openid）
        String openid = (String) json.get("openid");

       /* String s = decryptData(encryptedData, session_key, iv);
        System.out.println(s);*/
        return openid;
    }


    // 2、对encryptedData加密数据进行AES解密
       /* try {
            String result = WxAesUtils.decryptData(getURLDecoderString(encryptedData), session_key, getURLDecoderString(iv));
            if (null != result && result.length() > 0) {
                map.put("status", 1);
                map.put("msg", "解密成功");

                JSONObject userInfoJSON = JSONUtil.parseObj(result);
                Map userInfo = new HashMap();
                userInfo.put("openId", userInfoJSON.get("openId"));
                userInfo.put("nickName", userInfoJSON.get("nickName"));
                userInfo.put("gender", userInfoJSON.get("gender"));
                userInfo.put("city", userInfoJSON.get("city"));
                userInfo.put("province", userInfoJSON.get("province"));
                userInfo.put("country", userInfoJSON.get("country"));
                userInfo.put("avatarUrl", userInfoJSON.get("avatarUrl"));
                userInfo.put("unionId", userInfoJSON.get("unionId"));
                map.put("userInfo", userInfo);
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        map.put("status", 0);
        map.put("msg", "解密失败");*/
    // return null;
    //}


    private void register_wx(WX_zyl userInfo, String openid) {

        MarketUser marketUser = new MarketUser();
        marketUser.setNickname(userInfo.getUserInfo().getNickName());
        marketUser.setPassword(openid);
        marketUser.setAvatar(userInfo.getUserInfo().getAvatarUrl());
        marketUser.setWeixinOpenid(openid);
        marketUser.setStatus((byte) 0);
        marketUser.setUsername(userInfo.getUserInfo().getNickName());
        marketUser.setAddTime(new Date());
        marketUser.setGender((byte) 0);
        marketUser.setLastLoginIp("");
        marketUser.setSessionKey("");
        marketUser.setMobile("");
        marketCartService_zyl.insert(marketUser);

    }

    /**
     * 解码
     *
     * @param str
     * @return
     */
    public static String getURLDecoderString(String str) {

        String result = "";
        if (null == str) {
            return "";
        }
        try {
            result = java.net.URLDecoder.decode(str, "GBK");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }
}

